package com.x.gzcrm.web.security;

import com.x.gzcrm.model.Permission;
import com.x.gzcrm.service.IPermissionService;
import javafx.scene.web.WebView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.thymeleaf.util.StringUtils;

import javax.security.auth.login.AccountExpiredException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EnableWebSecurity
    public class SecurityConfig  extends WebSecurityConfigurerAdapter{
    @Autowired
    private IPermissionService iPermissionService;

    @Autowired
    private  VerifyCodeFilter verifyCodeFilter;

//    @Autowired
//    private  MyAuthenticationFailHandler authenticationFailHandler;

    @Bean
    public PasswordEncoder createPwdEncoder(){
        return  new BCryptPasswordEncoder();//进行密码进行多次的MD5加盐
    }

    /** 放行静态资源 */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/static/**");
        web.ignoring().antMatchers("/css/**");
        web.ignoring().antMatchers("/js/**");
        web.ignoring().antMatchers("/images/**");
        //解决服务注册url被拦截的问题
        web.ignoring().antMatchers("/resources/**");

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

//        //在账号密码验证前先判断验证码
        //http.addFilterBefore(verifyCodeFilter, UsernamePasswordAuthenticationFilter.class);

        //        in a frame because it set 'X-Frame-Options' to 'deny'
        http
                .headers()
                .frameOptions()
                .sameOrigin()
                .httpStrictTransportSecurity()
                .disable();

        //1.加载所有权限数据  授权
        List<Permission> pmslist=iPermissionService.findAllPermission();
        for (Permission pms : pmslist)
        {
            //2 告诉系统什么样的路径需要什么样的标识
            if(!StringUtils.isEmpty(pms.getPath()))
            {
                http.authorizeRequests().antMatchers(pms.getPath()).hasAnyAuthority(pms.getAuthorization_flag());
            }
        }


        //登录
        http
                .authorizeRequests()
                .antMatchers("/images/**","/css/**","/login","/code").permitAll()
//                .antMatchers("/css/**","/echarts/**","/font/**","/images/**","/lay/**","/index").permitAll()
                //.antMatchers("/user/**").hasRole("USER")//访问USer下的路径需要USER角色的权限
//                .antMatchers("/courseorder/detail").hasAnyAuthority("COURSEORDER_READ")
//                .antMatchers("/courseorder/delete").hasAnyAuthority("COURSEORDER_DELETE")


                .antMatchers("/login").permitAll()//代表login不需要拦截
                .antMatchers("/**").fullyAuthenticated()//设置所有访问路径都需要的认证（登录）
                .and()//完成上一个配置 进行下一个配置
                .csrf()
                .disable()
                .formLogin()
                .loginProcessingUrl("/login")//设置表单信息
                .loginPage("/login")//设置自己的登录页面
                .failureUrl("/login?error=true")
                .successForwardUrl("/index");
                //.defaultSuccessUrl("/index") // 设置默认登录成功后跳转的页面

       // .failureHandler(  "authenticationFailHandler"
        //session管理
        //session失效后跳转
        http.sessionManagement().invalidSessionUrl("/login");

        //解决中文乱码问题
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        http.addFilterBefore(filter,CsrfFilter.class);


    }


}
